// Optimized search function for chat.vue
export const handleOptimizedSearch = (searchQuery, chatList) => {
  const searchResults = [];
  
  if (!searchQuery.trim()) {
    return searchResults;
  }
  
  const keyword = searchQuery.trim();
  const keywordLower = keyword.toLowerCase();
  
  chatList.forEach((msg) => {
    msg.highlightedContent = null;
    const contentLower = msg.content.toLowerCase();
    const index = contentLower.indexOf(keywordLower);
    
    if (index !== -1) {
      msg.highlightedContent = highlightKeyword(msg.content, keyword);
      searchResults.push({
        messageId: msg.id,
        name: msg.name,
        datetime: msg.datetime,
        snippet: highlightKeyword(createSnippet(msg.content, index, keyword.length), keyword),
      });
    }
  });
  
  return searchResults;
};

function highlightKeyword(text, keyword) {
  const regex = new RegExp(keyword, 'gi');
  return text.replace(regex, (match) => `<mark>${match}</mark>`);
}

function createSnippet(text, index, keywordLen) {
  const snippetLength = 30;
  const start = Math.max(0, index - snippetLength);
  const end = Math.min(text.length, index + keywordLen + snippetLength);
  let snippet = text.substring(start, end);
  
  if (start > 0) {
    snippet = '...' + snippet;
  }
  if (end < text.length) {
    snippet += '...';
  }
  
  return snippet;
}